package com.yw.ffmpeg;

import android.media.MediaCodecInfo;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * @ProjectName: AndroidFFMpeg
 * @Package: com.yw.ffmpeg
 * @ClassName: MediaExtractorActivity
 * @Description: 媒体提取器
 * @Author: wei.yang
 * @CreateDate: 2021/5/8 16:43
 * @UpdateUser: 更新者：wei.yang
 * @UpdateDate: 2021/5/8 16:43
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public class MediaExtractorActivity extends BaseActivity {
    private Button btnSelectMedia;
    private TextView tvContent;
    private MediaExtractor mediaExtractor;
    //输出打印信息
    private StringBuilder sb = new StringBuilder();
    //视频轨ID
    private int videoTrackIndex = 0;
    //音频轨ID
    private int audioTrackIndex = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_extractor);
        initViews();
        initExtractor();
    }

    private void initViews() {
        btnSelectMedia = findViewById(R.id.btnSelectMedia);
        tvContent = findViewById(R.id.tvContent);
        btnSelectMedia.setOnClickListener(v -> {
            choiceVideo();
        });
    }

    @Override
    public void videoPathCallback(String vidoPath) {
        //设置Mp4路径
        try {
            mediaExtractor.setDataSource(vidoPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取轨道数量
        int count = mediaExtractor.getTrackCount();
        sb.append("媒体轨道数量：" + count).append("\n");
        for (int i = 0; i < count; i++) {
            //获取媒体轨道格式
            MediaFormat mediaFormat = mediaExtractor.getTrackFormat(i);
            sb.append("编号通道格式：" + i + "|" + mediaFormat.getString(MediaFormat.KEY_MIME));
            sb.append("\n");
        }
        //获取音频轨和视频轨的Index
        videoTrackIndex = getTrackIndex("video/");
        audioTrackIndex = getTrackIndex("audio/");

        getVideoFormatInfo();
//        tvContent.setText(sb.toString());
    }

    /**
     * 通过编码格式字符串对比获取指定轨道的方法
     *
     * @param targetTrack
     * @return
     */
    private int getTrackIndex(String targetTrack) {
        int count = mediaExtractor.getTrackCount();
        for (int i = 0; i < count; i++) {
            MediaFormat mediaFormat = mediaExtractor.getTrackFormat(i);
            if (mediaFormat.getString(MediaFormat.KEY_MIME).startsWith(targetTrack)) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 获取视频格式信息
     */
    private void getVideoFormatInfo() {
        mediaExtractor.selectTrack(videoTrackIndex);
        MediaFormat mediaFormat = mediaExtractor.getTrackFormat(videoTrackIndex);
        //获取语言格式内容
        String language = null;
        try {
            language = mediaFormat.getString(MediaFormat.KEY_LANGUAGE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取视频的宽度与高度
        Integer width = 0;
        Integer height = 0;
        try {
            //获取视频的宽度与高度
            width = mediaFormat.getInteger(MediaFormat.KEY_WIDTH);
            height = mediaFormat.getInteger(MediaFormat.KEY_HEIGHT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取视频播放总时长
        Long durationTime = 0l;
        try {
            durationTime = mediaFormat.getLong(MediaFormat.KEY_DURATION);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //获取视频缓存输出的最大大小
        Integer maxByteCount = 0;
        try {
            maxByteCount = mediaFormat.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*以下是不确定能否获取到的信息*/
        //获取采样率
        Integer sampleRate = 0;
        try {
            sampleRate = mediaFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取比特率(码率)
        Integer bitRate = 0;
        try {
            bitRate = mediaFormat.getInteger(MediaFormat.KEY_BIT_RATE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取声道数量
        Integer channelCount = 0;
        try {
            channelCount = mediaFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取最大宽度与最大高度
        Integer maxWidth = 0;
        Integer maxHeight = 0;
        try {
            maxWidth = mediaFormat.getInteger(MediaFormat.KEY_MAX_WIDTH);
            maxHeight = mediaFormat.getInteger(MediaFormat.KEY_MAX_HEIGHT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取颜色格式
        Integer colorFormat = 0;
        try {
            colorFormat = mediaFormat.getInteger(MediaFormat.KEY_COLOR_FORMAT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取帧率
        Integer fps = 0;
        try {
            fps = mediaFormat.getInteger(MediaFormat.KEY_FRAME_RATE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取分辨率
        Integer tileWidth = 0;
        Integer tileHeight = 0;
        try {
            tileWidth = mediaFormat.getInteger(MediaFormat.KEY_TILE_WIDTH);
            tileHeight = mediaFormat.getInteger(MediaFormat.KEY_TILE_HEIGHT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取网格行
        Integer gradRows = 0;
        try {
            gradRows = mediaFormat.getInteger(MediaFormat.KEY_GRID_ROWS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取网格列
        Integer ridColumn = 0;
        try {
            ridColumn = mediaFormat.getInteger(MediaFormat.KEY_GRID_COLUMNS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //PCM-编码 模拟信号编码
        Integer pcmEncoding = 0;
        try {
            pcmEncoding = mediaFormat.getInteger(MediaFormat.KEY_PCM_ENCODING);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //捕获率
        Float captureRate = 0f;
        try {
            captureRate = mediaFormat.getFloat(MediaFormat.KEY_CAPTURE_RATE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //是否是adts
        Integer isADTS = 0;
        try {
            isADTS = mediaFormat.getInteger(MediaFormat.KEY_IS_ADTS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        sb.
                append("语言格式：" + language).append("\n").
                append("视频宽高：" + width + "|" + height).append("\n").
                append("获取视频播放总时长：" + durationTime).append("\n").
                append("获取视频缓存输出的最大大小：" + maxByteCount).append("\n").
                append("获取采样率：" + sampleRate).append("\n").
                append("获取比特率(码率)：" + bitRate).append("\n").
                append("获取声道数量：" + channelCount).append("\n").
                append("获取最大宽度与最大高度：" + maxWidth + "|" + maxHeight).append("\n").
                append("获取颜色格式：" + colorFormat).append("\n").
                append("获取帧率：" + fps).append("\n").
                append("获取分辨率：" + tileWidth + "|" + tileHeight).append("\n").
                append("获取网格行：" + gradRows).append("\n").
                append("获取网格列：" + ridColumn).append("\n").
                append("PCM-编码 模拟信号编码：" + pcmEncoding).append("\n").
                append("捕获率：" + captureRate).append("\n").
                append("是否是adts：" + isADTS).append("\n");
        tvContent.setText(sb.toString());
    }

    private void initExtractor() {
        mediaExtractor = new MediaExtractor();

    }

    /**
     * 选择指定的轨道，并开始读取轨道中的数据
     */
    private void selectTargetTrack(){
        mediaExtractor.selectTrack(videoTrackIndex);
        while (true){
            ByteBuffer buffer = ByteBuffer.allocate(1024*1024);
            int sampleSize = mediaExtractor.readSampleData(buffer,0);
            if(sampleSize<0){
                break;
            }
            //读取下一帧
            mediaExtractor.advance();

        }

    }
}
